package com.yunhe.authority.service.app.impl;

import com.yunhe.authority.domain.app.AppPushInfo;
import com.yunhe.authority.domain.authority.User;
import com.yunhe.authority.repository.app.AppPushInfoRepository;
import com.yunhe.authority.service.app.AppPushInfoService;
import com.yunhe.common.util.JPushForYQTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author zhengbo
 * @date 2021/11/11 14:14
 */
@Service
@Slf4j
public class AppPushInfoServiceImpl implements AppPushInfoService {

    private static final Integer MAX_NUMBER = 999;

    @Resource
    private AppPushInfoRepository appPushInfoRepository;

    @Override
    public void recordUserAppInfo(Long userId,
                                  String registrationId,
                                  String deviceId,
                                  String systemOs) {

        AppPushInfo byUserIdAndDeviceId = appPushInfoRepository.findByUserIdAndDeviceId(userId, deviceId);
        //先查询该账号是否在该设备中登录过
        if (byUserIdAndDeviceId != null) {
            //如果登陆过但是registrationId不相同，说明可能卸载重新安装，更新这个值。相同就忽略
            if (!registrationId.equals(byUserIdAndDeviceId.getRegistrationId())) {
                byUserIdAndDeviceId.setRegistrationId(registrationId);
                appPushInfoRepository.save(byUserIdAndDeviceId);
            }
        } else {
            AppPushInfo appPushInfo = new AppPushInfo();
            appPushInfo.setUserId(userId);
            appPushInfo.setRegistrationId(registrationId);
            appPushInfo.setDeviceId(deviceId);
            appPushInfo.setSystemOs(systemOs);
            AppPushInfo newAppPushInfo = appPushInfoRepository.save(appPushInfo);
            //绑定用户
            appPushInfoRepository.bindUser(userId, newAppPushInfo.getId());
        }
    }

    @Override
    public void deleteUserAppInfo(Long userId, String registrationId, String deviceId) {
        appPushInfoRepository.deleteByUserIdAndDeviceIdAndRegistrationId(userId, registrationId, deviceId);
    }

    @Override
    public void pushMessageToUserList(String userIds,
                                      String notificationTitle,
                                      String msgTitle,
                                      String msgContent,
                                      Map<String, String> extras) {

        String[] strings = userIds.split(",");
        List<Long> userIdList = new ArrayList<>();
        for (String userId : strings) {
            userIdList.add(Long.valueOf(userId));
        }

        List<AppPushInfo> appPushInfos = appPushInfoRepository.findByUserIdList(userIdList);
        pushMessage(notificationTitle, msgTitle, msgContent, extras, appPushInfos);


    }

    @Override
    public void pushMessageToStationUser(Long stationId,
                                         String notificationTitle,
                                         String msgTitle,
                                         String msgContent,
                                         Map<String, String> extras) {

        List<AppPushInfo> appPushInfos = appPushInfoRepository.findByStationId(stationId);
        pushMessage(notificationTitle, msgTitle, msgContent, extras, appPushInfos);


    }

    /**
     * 推送消息
     * @param notificationTitle 通知标题
     * @param msgTitle  消息标题
     * @param msgContent    消息内容
     * @param extras    额外字段
     * @param appPushInfos  app用户信息
     */
    private void pushMessage(String notificationTitle, String msgTitle, String msgContent, Map<String, String> extras, List<AppPushInfo> appPushInfos) {
        List<String> registrationIdList = appPushInfos.stream().map(AppPushInfo::getRegistrationId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(registrationIdList)) {
            //做分割处理，一次处理999条
            int limit = countStep(registrationIdList.size());
            //使用流遍历操做
            List<List<String>> mgList = new ArrayList<>();
            Stream.iterate(0, n -> n + 1).limit(limit).forEach(i -> mgList.add(registrationIdList.stream().skip(i * MAX_NUMBER).limit(MAX_NUMBER).collect(Collectors.toList())));
            mgList.forEach(subList -> JPushForYQTUtil.sendToRegistrationId(subList, notificationTitle, msgTitle, msgContent, extras));
        }
    }

    /**
     * 计算切分次数
     */
    private static Integer countStep(Integer size) {
        return (size + MAX_NUMBER - 1) / MAX_NUMBER;
    }
}
